<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="900px" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入文章标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文章状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.ARTICLE_STATUS)"
                        :key="dict.value" :label="parseInt(dict.value)"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="文章内容">
        <Editor v-model="form.content" :min-height="300"/>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="封面图片" prop="coverImage">
            <el-upload
              class="avatar-uploader"
              :action="uploadImgUrl"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload">
              <img v-if="form.coverImage" :src="form.coverImage" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文章视频" prop="videoUrl">
            <el-upload
              class="video-uploader"
              :action="uploadVideoUrl"
              :show-file-list="false"
              :on-success="handleVideoSuccess"
              :before-upload="beforeVideoUpload">
              <video v-if="form.videoUrl" :src="form.videoUrl" class="video-preview" controls></video>
              <i v-else class="el-icon-plus video-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="文章话题" prop="topicCode">
        <el-select
          v-model="form.topicCode"
          placeholder="请选择文章话题"
          style="width: 300px;"
          filterable>
          <el-option
            v-for="item in topicOptions"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import * as ArticleApi from '@/api/article/article';
  import ImageUpload from '@/components/ImageUpload';
  import Editor from '@/components/Editor';
  import { getTopicPage } from '@/api/topic/topic';

  export default {
    name: "ArticleForm",
    components: {
      ImageUpload,
      Editor,
    },
    dicts: ['article_status'],
    data() {
      return {
        dialogVisible: false,
        title: "",
        form: {
          id: undefined,
          title: undefined,
          content: undefined,
          coverImage: undefined,
          videoUrl: undefined,
          status: undefined,
          topicId: undefined,
          productId: undefined,
        },
        rules: {
          title: [{ required: true, message: "文章标题不能为空", trigger: "blur" }],
          status: [{ required: true, message: "文章状态不能为空", trigger: "change" }],
          productId: [{ required: true, message: '商品id不能为空', trigger: 'blur' }],
        },
        uploadImgUrl: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload",
        uploadVideoUrl: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload",
        topicOptions: [],
        topicQuery: {
          pageNo: 1,
          pageSize: 100,
          isAllData: true
        }
      };
    },
    methods: {
      /** 打开弹窗 */
      async open(id) {
        this.reset();
        this.dialogVisible = true;

        try {
          const res = await getTopicPage(this.topicQuery);
          if (res.data && res.data.list) {
            this.topicOptions = res.data.list;
          }
        } catch (error) {
          console.error('获取话题列表失败:', error);
          this.$modal.msgError('获取话题列表失败');
        }

        if (id) {
          this.title = "修改文章";
          try {
            const res = await ArticleApi.getArticle(id);
            this.form = res.data;
          } catch (error) {
            console.error('获取文章数据失败:', error);
            this.$modal.msgError('获取文章数据失败');
          }
        } else {
          this.title = "新增文章";
        }
      },
      /** 提交按钮 */
      async submitForm() {
        await this.$refs["form"].validate();
        try {
          const data = this.form;
          if (data.id) {
            await ArticleApi.updateArticle(data);
            this.$modal.msgSuccess("修改成功");
            this.dialogVisible = false;
            this.$emit('success');
            return;
          }
          await ArticleApi.createArticle(data);
          this.$modal.msgSuccess("新增成功");
          this.dialogVisible = false;
          this.$emit('success');
        } finally {
        }
      },
      /** 表单重置 */
      reset() {
        this.form = {
          id: undefined,
          title: undefined,
          content: undefined,
          coverImage: undefined,
          videoUrl: undefined,
          status: undefined,
          topicId: undefined,
          productId: undefined,
        };
        this.resetForm("form");
      },
      handleImageSuccess(res, file) {
        this.form.coverImage = res.data;
      },
      beforeImageUpload(file) {
        const isImage = file.type.indexOf('image') !== -1;
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isImage) {
          this.$message.error('上传封面图片只能是图片格式!');
          return false;
        }
        if (!isLt2M) {
          this.$message.error('上传封面图片大小不能超过 2MB!');
          return false;
        }
        return true;
      },
      handleVideoSuccess(res, file) {
        this.form.videoUrl = res.data;
      },
      beforeVideoUpload(file) {
        const isVideo = file.type.indexOf('video') !== -1;
        const isLt50M = file.size / 1024 / 1024 < 50;

        if (!isVideo) {
          this.$message.error('上传视频只能是视频格式!');
          return false;
        }
        if (!isLt50M) {
          this.$message.error('上传视频大小不能超过 50MB!');
          return false;
        }
        return true;
      },
      /** 取消按钮 */
      cancel() {
        this.dialogVisible = false;
        this.reset();
      },
    }
  };
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}

.avatar-uploader,
.video-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 300px;
}

.avatar-uploader:hover,
.video-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon,
.video-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 200px;
  line-height: 200px;
  text-align: center;
}

.avatar,
.video-preview {
  width: 300px;
  height: 200px;
  display: block;
  object-fit: cover;
}

.el-dialog__body {
  padding: 20px 30px;
}

.el-form-item__label {
  font-weight: 500;
}

.el-select {
  width: 100%;
}

.el-select .el-input {
  width: 300px;
}
</style>
